package com.gethb.prod.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gethb.prod.vo.KlineDataInVo;
import com.gethb.prod.vo.MarketDataOutVo;
import com.gethb.prod.vo.Result;
import com.gethb.pub.utils.UrlParamsBuilder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.gethb.prod.service.IGetKlineService;

@Component("getKlineService")
public class GetKlineServiceImpl implements IGetKlineService {

    private static final Logger LOG = LoggerFactory.getLogger(GetKlineServiceImpl.class);

    private Environment env;

    private static final OkHttpClient okHttpClient = new OkHttpClient();

    @Autowired
    public void setEnv(Environment env) {
        this.env = env;
    }

    @Override
    public Result<MarketDataOutVo> getMarketData(KlineDataInVo inVo) throws Exception {
        String serverUrl = env.getProperty("dataServerUrl");
        UrlParamsBuilder builder = UrlParamsBuilder.build()
                .putToUrl("symbol", inVo.getSymbol())
                .putToUrl("period", inVo.getPeriod())
                .putToUrl("size", inVo.getSize());
//
        serverUrl += "/kline/marketData" + builder.buildUrl();
        LOG.info("serverUrl--->" + serverUrl);
        Request executeRequest = new Request.Builder().url(serverUrl).build();

        Response response = okHttpClient.newCall(executeRequest).execute();
        if (response.code() == 200) {
            assert response.body() != null;
            JSONObject jsonObject = JSON.parseObject(response.body().string());
            Result<MarketDataOutVo> result = new Result<>();
            result.setCode(jsonObject.getInteger("code"));
            result.setMsg(jsonObject.getString("msg"));
            result.setBody(jsonObject.getObject("body", MarketDataOutVo.class));
            return result;

        } else {
            return Result.exception(response.toString());
        }
    }
}
